import os
import json
from datetime import datetime, timedelta
from collections import defaultdict
from pyecharts import options as opts
from pyecharts.charts import Line
from pyecharts.globals import ThemeType
import time
import json
import sys
import os
from datetime import datetime
from datetime import datetime, timedelta,time as dtime
from pathlib import Path
import logging
import shutil
from logging.handlers import TimedRotatingFileHandler
import requests
# 全局变量存储解析后的配置
config_dict = {}
# 全局标志：是否已达到最大配置键
has_reached_max = False
# 全局缓存：最大配置键的值
max_value = None

def parse_config(config_str):
    """
    解析配置字符串并保存到全局变量config_dict中
    """
    global config_dict, has_reached_max, max_value
    
    # 重置所有状态
    config_dict = {}
    has_reached_max = False
    max_value = None
    
    if not config_str:
        return
    
    # 分割多个配置（如果有逗号）
    if ',' in config_str:
        items = config_str.split(',')
        for item in items:
            # 分割键值对
            if ':' in item:
                key, value = item.split(':', 1)
                key = key.strip()
                value = value.strip()
                if key and value:
                    try:
                        # 转换为整数以便数值比较
                        config_dict[int(key)] = value
                    except ValueError:
                        # 忽略无法转换为整数的键
                        pass
    
    # 处理单个键值对
    elif ':' in config_str:
        key, value = config_str.split(':', 1)
        key = key.strip()
        value = value.strip()
        if key and value:
            try:
                config_dict[int(key)] = value
            except ValueError:
                pass
    
    # 处理单个数值
    else:
        # 对于单个数值，我们使用0作为特殊键
        config_dict[0] = config_str.strip()
    
    # 如果配置中有键值对，设置最大值的缓存
    if 0 not in config_dict and config_dict:
        max_key = max(config_dict.keys())
        max_value = config_dict[max_key]
def get_closest_value(input_value):
    """
    获取最接近输入值的配置金额
    规则:
    1. 如果是单个数值配置，返回该值
    2. 如果已经达到过最大配置键，直接返回最大配置键的值
    3. 否则找到小于等于输入值的最大键对应的值
    4. 如果输入值大于最大配置键，返回最大配置键的值并设置状态
    """
    global has_reached_max,init_money
    
    if not config_dict:
        return None
    
    # 1. 如果是单个数值配置
    if 0 in config_dict:
        return config_dict[0]
    
    # 2. 如果已经达到过最大配置键
    if has_reached_max:
        return max_value
    
    # 获取所有配置键并排序
    keys = sorted(config_dict.keys())
    max_key = keys[-1]
    
    # 3. 输入值大于等于最大配置键
    if input_value >= max_key:
        # 设置状态：已达到最大配置键
        has_reached_max = True
        return max_value
    
    # 4. 找到所有小于等于输入值的键
    candidate_keys = [k for k in keys if k <= input_value]
    
    if candidate_keys:
        # 返回小于等于输入值的最大键对应的值
        return_val = config_dict[candidate_keys[-1]]
        if init_money >= int(return_val):
            return init_money
        else:
            return return_val
    else:
        # 输入值小于所有配置键，返回最小键的值
        if init_money >= int(config_dict[keys[0]]):
            return init_money
        else:
            return config_dict[keys[0]]
def group_data_by_date(data):
    """按上一天CYCLE_START_HOUR点到下一天CYCLE_END_HOUR点作为一个周期分组数据并按期号升序排列"""
    daily_data = defaultdict(list)
    for item in data['items']:
        open_time = datetime.strptime(item['open_time'], "%Y-%m-%d %H:%M:%S")

        # 计算周期的起始和结束时间点
        if open_time.hour >= CYCLE_START_HOUR:
            # 开奖时间在起始小时之后，周期起始为当天
            cycle_start_date = open_time.date()
        else:
            # 开奖时间在起始小时之前，周期起始为前一天
            cycle_start_date = open_time.date() - timedelta(days=1)

        # 计算周期起始和结束的完整时间
        cycle_start = datetime.combine(cycle_start_date, datetime.min.time()) + timedelta(hours=CYCLE_START_HOUR)
        cycle_end = cycle_start + timedelta(days=1)

        # 处理特殊的24点情况
        if CYCLE_END_HOUR != 24:
            cycle_end = datetime.combine(cycle_start_date + timedelta(days=1), datetime.min.time()) + timedelta(
                hours=CYCLE_END_HOUR)
            
        # 确定当前开奖时间属于哪个周期（以周期结束日期作为周期标识）
        if cycle_start <= open_time < cycle_end:
            cycle_date = cycle_start_date + timedelta(days=1)
        else:
            # 处理边界情况
            if open_time >= cycle_end:
                cycle_date = cycle_start_date + timedelta(days=2)
            else:
                cycle_date = cycle_start_date + timedelta(days=1)

        daily_data[cycle_date].append(item)

    # 对每天的数据按期号升序排列

    # 如果时间等于当前天，判断下一天是否有数据，有的话判断日期是否在范围内，如果在范围内就加入
    #today = datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
    today_str = str(datetime.now().strftime( "%Y-%m-%d %H:%M:%S"))
    today = datetime.strptime(today_str, "%Y-%m-%d %H:%M:%S")
    next_today = datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(
                hours=CYCLE_END_HOUR)
    today_today = datetime.combine(today, datetime.min.time()) + timedelta(
                hours=CYCLE_START_HOUR)
    if daily_data[next_today.date()]:
        next_data = daily_data[next_today.date()]
        for item in next_data:
             open_time1 = datetime.strptime(item['open_time'], "%Y-%m-%d %H:%M:%S")
             if today_today <= open_time1 < next_today:
                daily_data[today.date()].append(item)

    for date in daily_data:
        daily_data[date] = sorted(daily_data[date], key=lambda x: int(x['issue_no']))

    return daily_data

    return daily_data
if __name__ == "__main__":
    '''with open("spider_char_car_data_20250821/merged_20250821_copy.json", 'r', encoding='utf-8') as f:
            data = json.load(f)
          # 分析数据
        # 过滤出当天数据
    filtered_items = [item for item in data.get('items', [])]
    seen_issues = {}
    unique_items = []
        # 先按open_time降序排序，确保每个issue_no只保留最新的一条
    for item in sorted(filtered_items, key=lambda x: x.get('open_time', ''), reverse=True):
        issue_no = item.get('issue_no')
        if issue_no and issue_no not in seen_issues:
            seen_issues[issue_no] = True
            unique_items.append(item)
    data = {"items": sorted(unique_items, key=lambda x: x.get('open_time', ''))}
    global  CYCLE_START_HOUR,CYCLE_END_HOUR
    CYCLE_START_HOUR = 24
    CYCLE_END_HOUR = 23
    daily_data = group_data_by_date(data)
   
    print(daily_data)'''
    global init_money
    init_money = 5
    parse_config('1:10,4:20')
    # 初始押注金额,默认为 10块起步
    init_money = int(get_closest_value(1))
    print(init_money)